<template>
    <view class="content-video">
        <view class="content-video-back" @click="goback"><uni-icons type="back" color="#333" size="30"></uni-icons></view>
        <div id="container">
            <video id="video-local" autoplay playsinline :controls="false"></video>
            <!-- <button id="showVideo">打开摄像头</button>
            <button id="stopVideo">关闭摄像头</button>
            <p>显示摄像头预览的内容，网页上由元素video来呈现。</p>
            <p>点击打开摄像头按钮后，浏览器会询问是否允许，请点击“允许”。</p> -->
            <div id="errorMsg"></div>
            <div id="tipMsg"></div>
            <canvas id="canvas"></canvas>
        </div>
        <div class="content-tips">
            请将摄像头对准人脸
        </div>
    </view>
</template>
  
<script setup>
import { reactive, getCurrentInstance, onMounted, ref } from "vue";
import { setAuthorization, getAuthorization } from "@/utils/auth.js";
import { onLoad } from "@dcloudio/uni-app";

const constraints = (window.constraints = {
    audio: false,
    video: true,
});
function showErrMsg(msg, error) {
    const errorElement = document.querySelector("#errorMsg");
    errorElement.innerHTML += `<p>${msg}</p>`;
    if (typeof error !== "undefined") {
    }
}

function showMsg(msg) {
    const msgEle = document.querySelector("#tipMsg");
    msgEle.innerHTML += `<p>-> ${msg}</p>`;
}
let videoEle = null;
let setInt = null
function gotStream(stream) {
    videoEle = document.querySelector("video");
    const videoTracks = stream.getVideoTracks();
    showMsg(`正在使用的设备: ${videoTracks[0].label}`);
    window.stream = stream;
    videoEle.srcObject = stream;
    setInt = setInterval(() => {
        setImage()
    }, 2000)
}

function stopVideo(e) {
    const videoElem = document.querySelector("video");
    const stream = videoElem.srcObject;

    // document.querySelector("#showVideo").disabled = false; // 允许开启

    if (stream == null) {
        return;
    }
    const tracks = stream.getTracks();

    tracks.forEach(function (track) {
        track.stop();
    });
    videoElem.srcObject = null;
}

async function openCamera(e) {
    try {
        showMsg("正在打开摄像头");
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        showMsg("获取到了stream");
        gotStream(stream);
        e.target.disabled = true;
    } catch (err) {
        // onErr(err);
    }
}

let emits = defineEmits(["update:goBackClose", "update:authImgList", "startAuthFn"])

let imgList = ref([])
const formData = new FormData();

import axios from 'axios'
const parseBlob = async (base64) => {
    let arr = base64.split(",");
    let mime = arr[0].match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    for (let i = 0; i < n; i++) {
        u8arr[i] = bstr.charCodeAt(i);
    }
    let file2 = new File([u8arr], "test.png", { type: "image/png" });
    // 上传文件
    let tokenObj = getAuthorization("token") ? JSON.parse(getAuthorization("token")) : ""
    let token = tokenObj.AccessToken
    let config = {
        headers: {
            'Content-type': 'multipart/form-data',
            "Authorization": "Bearer " + token
        }
    }
    imgList.value.push(file2)
    formData.append("file", file2);
    if( imgList.value.length < 4){
        return
    }
    formData.append("groupCode", '99999999');
    axios.post('/api/app/api/G/user-heibai/v1/Files', formData, config).then(res => {
        console.log(res.data.data,'res.data')
        emits("update:authImgList", res.data.data)
        emits("startAuthFn")
        stopVideo()
        clearInterval(setInt)
        // 上传成功后的处理
    }, err => {
        // 出现错误时的处理
    })
    stopVideo
};

const setImage = () => {
    videoEle.setAttribute("crossOrigin", "anonymous"); // 处理跨域，H5需后台支持，请求的视频资源响应投标需有Access-Control-Allow-Origin
    // videoEle.setAttribute("src", url);
    let _width = videoEle.offsetWidth;
    let _height = videoEle.offsetHeight;
    videoEle.setAttribute("width", _width/2);
    videoEle.setAttribute("height", _height/2);
    videoEle.setAttribute("preload", "auto");
    let canvas = document.createElement("canvas");
    let width = videoEle.offsetWidth; // canvas的尺寸和图片一样
    let height = videoEle.offsetHeight;
    canvas.width = width/2;
    canvas.height = height/2;
    canvas.getContext("2d").drawImage(videoEle, 0, 0, width/2, height/2); // 绘制canvas
    const dataURL = canvas.toDataURL("image/png"); // 转换为base64
    parseBlob(dataURL);
};


const goback = () => {
    emits("update:goBackClose", false)
}

onMounted(() => {
    openCamera();
});
</script>
  
<style lang="scss" scoped>
.content {
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(255, 255, 255, 0.4);
    backdrop-filter: blur(130px);

    .login-image {
        margin-top: -200rpx;
        display: flex;
        justify-content: center;
    }

    .login-image-text {
        margin-top: 15rpx;
        text-align: center;
        font-weight: 700;
        font-size: 32rpx;
        line-height: 150%;
        color: #223263;
    }
}

.login-form {
    margin-top: 20px;
}

.unilogin-form-item {
    display: flex;
    width: calc(100vw - 40rpx);
    border: 2rpx solid #f2f2f2;
    background: #fff;
    align-items: center;
    padding: 10rpx 20rpx;
    box-sizing: border-box;
    margin-bottom: 20rpx;
    border-radius: 10rpx;

    .login-item-input {
        width: 100%;
        margin-left: 10rpx;
        height: 72rpx;
        line-height: 72rpx;
        padding: 0;
        font-size: 60rpx;
    }
}

::v-deep .van-field__control {
    font-size: 32rpx;
    height: 72rpx;
    line-height: 72rpx;
}

.column1 {
    border: 2rpx solid #2596d7 !important;
    color: #2596d7;
}

.van-button {
    height: 120rpx;
    background: radial-gradient(125% 125% at 85.42% 0%, #85d3ff 0%, #2596d7 100%);
    border-radius: 8px;
    font-style: normal;
    font-weight: 600;
    font-size: 36rpx;
    color: #fff;
    border: none;
}

input {
    -webkit-tap-highlight-color: rgba(255, 255, 255, 0);
    -webkit-user-select: none;
    -moz-user-focus: none;
    -moz-user-select: none;
    -webkit-appearance: none;
    outline: none;
    border: none;
}

.content-video {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    z-index: 99;
}

// #video-local {
//     position: fixed;
//     z-index: 998;
//     top: 0;
//     left: 0;
//     width: 100vw;
//     height: 100vh;
//     transform: rotateY(180deg);
// }

.start-btn {
    position: fixed;
    z-index: 997;
    bottom: 0;
    left: 0;
}

.content-video-back {
    position: fixed;
    z-index: 999;
    top: 20rpx;
    left: 20rpx;
}

video::-webkit-media-controls-fullscreen-button {
    display: none;
}

:deep(.uni-video-cover) {
    display: none !important;
}

:deep(.uni-video-bar) {
    display: none !important;
}

#container {
    width: 160px;
    height: 160px;
    overflow: hidden;
    position: relative;
    margin: 150px auto;
    border-radius: 50%;
}

#video-local {
    width: 300px;
    height: 225px;
    display: inline-block;
    line-height: 0;
    overflow: hidden;
    position: relative;
    transform: scaleX(-1);
    position: absolute;
    top: 0;
    left: 0;
    transform: translateX(-20%);
}

.content-tips {
    text-align: center;
}
</style>